package cc.yiueil.synergism;

import java.util.ArrayList;
import java.util.List;

public class Main {
    public static void main(String[] args) throws InterruptedException {
        int providerNum = 5;
        // 生产速度
        List<Thread> threadList = new ArrayList<>();
        int providerCreateProductSpeed = 5;
        int consumerNum = 2;
        int consumerUseProductSpeed = 1;
        ProductQueue<Product> productQueue = new ProductQueue<Product>();
        for (int i = 0; i < providerNum; i++) {
            int finalI = i;
            Thread thread = new Thread(() -> {
                while (!Thread.currentThread().isInterrupted()) {
                    // 1s生成一个
                    try {
                        Thread.sleep(providerCreateProductSpeed * 1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    Product product = new Product(String.valueOf(finalI));
                    productQueue.addProduct(product);
                    System.out.println("provider: " + product.getName());
                }
            });
            thread.start();
            threadList.add(thread);
        }
        for (int i = 0; i < consumerNum; i++) {
            Thread thread = new Thread(() -> {
                while (!Thread.currentThread().isInterrupted()) {
                    try {
                        Product product = productQueue.getProduct();
                        Thread.sleep(consumerUseProductSpeed * 1000);
                        System.out.println("consumer: " + product.getName());
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            });
            thread.start();
            threadList.add(thread);
        }
        for (Thread thread : threadList) {
            thread.join();
        }
    }
}

class Product {
    private String name;

    public Product(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}
